package com.dana.job.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.constants.CacheConstant;
import com.core.constants.Constants;
import com.dana.job.domain.Exam;
import com.dana.job.mapper.ExamMapper;
import com.dana.redis.service.RedisService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class ExamXxlJob {
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private RedisService redisService;
    @XxlJob("examListOrganizeHandler")
    public void examListOrganizeHandler(){
        log.info("**********定时任务开始执行*******");
        List<Exam> unFinishList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                .gt(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(unFinishList,CacheConstant.EXAM_UNFINISHED_LIST);
        List<Exam> historyList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                .le(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(historyList,CacheConstant.EXAM_HISTORY_LIST);
    }



    //刷新缓存逻辑
    public void refreshCache(List<Exam> examList,String examListKey) {
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }
        //使用Map批量插入竞赛基本信息
        Map<String, Exam> examMap = new HashMap<>();
        //使用list插入竞赛id,根据竞赛id去查询基本信息
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        //批量插入
        redisService.multiSet(examMap);  //刷新详情缓存
        //可能之前redis会有和数据库重复的数据,删除后再缓存数据库到redis
        redisService.deleteObject(examListKey);
        //将竞赛id缓存到redis
        redisService.rightPushAll(examListKey, examIdList);
    }

    private String getDetailKey(Long examId) {
        return CacheConstant.EXAM_DETAIL + examId;
    }
}
